package com.itheima.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.JedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Reference
    MemberService memberService;

    @Autowired
    JedisUtil jedisUtil;

    @RequestMapping("/check")
    public Result check(@RequestBody Map map, HttpServletRequest request){
     //校验页面用户输入的验证码是否正确，不正确返回 验证码错误
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        String codeInRedis = jedisUtil.get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
         if (codeInRedis==null || !codeInRedis.equals(validateCode)){
              return  Result.error("您输入的验证码有误");
         }
        //如果验证码校验正确 根据电话号码判断是否是会员， 如果不是自动注册为会员
          Member member=memberService.findByTelephone(telephone);
         if (member==null){
             member = new Member();
             member.setPhoneNumber(telephone);
             member.setRegTime(new Date());
      member= memberService.add(member);
         }

        //登录成功将用户信息写入session
         request.getSession().setAttribute("member",member);
        return Result.success("登录成功");
    }

}
